/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zhihu.matisse.engine.impl;

import com.zhihu.matisse.engine.ImageEngine;
import com.zhihu.matisse.utils.L;
import com.zhihu.matisse.utils.UriUtils;
import ohos.agp.components.Image;
import ohos.agp.components.element.PixelMapElement;
import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.utils.net.Uri;

public class SimpleImageEngine implements ImageEngine {
    @Override
    public void loadThumbnail(Context context, int resize, PixelMap placeholder, Image imageView, Uri uri) {
        imageView.setScaleMode(Image.ScaleMode.CLIP_CENTER);
        if (placeholder != null){
            imageView.setBackground(new PixelMapElement(placeholder));
        }
        loadImage(context,resize,resize,imageView,uri);
    }

    @Override
    public void loadGifThumbnail(Context context, int resize, PixelMap placeholder, Image imageView, Uri uri) {
        imageView.setScaleMode(Image.ScaleMode.CLIP_CENTER);
        if (placeholder != null){
            imageView.setBackground(new PixelMapElement(placeholder));
        }
        loadImage(context,resize,resize,imageView,uri);
    }

    @Override
    public void loadImage(Context context, int resizeX, int resizeY, Image imageView, Uri uri) {
        try {
            ImageSource imageSource = UriUtils.uriToImageSource(context, uri);
            if (imageSource != null){
                setImage(imageSource,resizeX,resizeY,imageView);
            }
        } catch (Exception e) {
            L.d(e.getMessage());
        }
    }
    private void setImage(ImageSource imageSource,int resizeX, int resizeY, Image imageView){
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        decodingOptions.editable = true;
        decodingOptions.sampleSize = 1;
        if (resizeX != 0 && resizeY != 0){
            decodingOptions.desiredSize = new Size(resizeX,resizeY);
        }
        PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);

        imageView.setPixelMap(pixelMap);
    }

    @Override
    public void loadGifImage(Context context, int resizeX, int resizeY, Image imageView, Uri uri) {
        loadImage(context,resizeX,resizeY,imageView,uri);
    }

    @Override
    public boolean supportAnimatedGif() {
        return false;
    }
}
